package com.hhd.form.table.field;

import com.hhd.base.utils.CommonUtils;
import com.hhd.form.entity.DesignFormFieldDefinition;
import com.hhd.form.entity.DesignFormTableFieldMeta;
import com.hhd.form.entity.DesignFormTableMeta;
import com.hhd.form.mapper.DesignFormMapper;
import com.hhd.form.service.IDesignFormTableFieldMetaService;
import com.hhd.form.service.IDesignFormTableMetaService;
import com.hhd.form.table.db.DBOperator;
import com.hhd.form.vo.FormDefinition;
import com.hhd.form.vo.SubFormDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

@Component
public class FormFieldBuilder {
    @Autowired
    DesignFormMapper formMapper;
    @Autowired
    IDesignFormTableMetaService tableMetaService;
    @Autowired
    IDesignFormTableFieldMetaService fieldMetaService;
    @Autowired
    DBOperator dbOperator;
    private static final String fieldPrefix = "field_";

    public void buildFormFields(FormDefinition fomDefinition) {
        createFormFields(fomDefinition);
        List<SubFormDefinition> subForms = fomDefinition.getSubForms();
        if (CommonUtils.isEmpty(subForms)) return;
        for (SubFormDefinition subForm : subForms) {
            createFormFields(subForm);
        }
    }

    private void createFormFields(FormDefinition fomDefinition) {
        String tableName = fomDefinition.getTableName();
        DesignFormTableMeta tableMeta = getTableMetaByTableName(tableName); //这个表记录一定存在
        List<DesignFormFieldDefinition> fields = fomDefinition.getFields();
        List<DesignFormTableFieldMeta> fieldMetas = fieldMetaService.lambdaQuery().eq(DesignFormTableFieldMeta::getTableId, tableMeta.getId()).list();
        int index = getFieldLastIndex(fieldMetas);
        for (DesignFormFieldDefinition field : fields) {
            if (CommonUtils.isEmpty(field.getFieldName()) || notExistField(field.getFieldName(), fieldMetas)) {
                DesignFormTableFieldMeta fieldMeta = createFormField(field, fomDefinition, index, tableMeta);
                index = fieldMeta.getFieldIndex();
                fieldMetaService.save(fieldMeta);
                doCreateTableField(field, fieldMeta, tableMeta, fomDefinition);
            } else {
                Optional<DesignFormTableFieldMeta> fieldMeta = fieldMetas.stream().filter(f -> f.getFieldName().equals(field.getFieldName())).findAny();
                updateFieldComment(field, fieldMeta.get(), tableMeta, fieldMeta);
                fieldMetaService.updateById(fieldMeta.get());
            }
        }
//        fomDefinition.setFieldLastIndex(index);
    }

    private void doCreateTableField(DesignFormFieldDefinition field, DesignFormTableFieldMeta fieldMeta, DesignFormTableMeta tableMeta, FormDefinition fomDefinition) {
        dbOperator.doCreateTableField(field, fieldMeta, tableMeta, fomDefinition);
        fieldMetaService.updateById(fieldMeta);
    }

    private void updateFieldComment(DesignFormFieldDefinition field, DesignFormTableFieldMeta designFormTableFieldMeta, DesignFormTableMeta tableMeta, Optional<DesignFormTableFieldMeta> fieldMeta) {
        fieldMeta.get().setComment(field.getLabel());
        dbOperator.updateFieldComment(field, designFormTableFieldMeta, tableMeta);
    }

    private DesignFormTableFieldMeta createFormField(DesignFormFieldDefinition field, FormDefinition fomDefinition, int index, DesignFormTableMeta tableMeta) {
        DesignFormTableFieldMeta fieldMeta = new DesignFormTableFieldMeta();
        fieldMeta.setTableId(tableMeta.getId());
        if (CommonUtils.isEmpty(field.getFieldName())) {
            fieldMeta.setFieldIndex(++index);
            fieldMeta.setFieldName(createFieldName(index));
            field.setFieldName(createFieldName(index));
        } else {
            fieldMeta.setFieldIndex(index);
            fieldMeta.setFieldName(field.getFieldName());
        }
        fieldMeta.setComment(field.getLabel());
        return fieldMeta;
    }

    private boolean notExistField(String fieldName, List<DesignFormTableFieldMeta> fieldMetas) {
        for (DesignFormTableFieldMeta fieldMeta : fieldMetas) {
            if (fieldMeta.getFieldName().equals(fieldName))
                return false;
        }
        return true;
    }

    private String createFieldName(int index) {
        return fieldPrefix + createFieldIndexStr(index);
    }

    private String createFieldIndexStr(int index) {
        StringBuilder res = new StringBuilder(index + "");
        while (res.length() < 5) res.insert(0, "0");
        return res.toString();
    }

    private int getFieldLastIndex(List<DesignFormTableFieldMeta> fieldMetas) {
        int index = 0;
        for (DesignFormTableFieldMeta fieldMeta : fieldMetas) {
            index = Math.max(fieldMeta.getFieldIndex(), index);
        }
        return index;
    }

    private DesignFormTableMeta getTableMetaByTableName(String tableName) {
        List<DesignFormTableMeta> tableMetas = tableMetaService.lambdaQuery().eq(DesignFormTableMeta::getTableName, tableName).list();
        if (!CommonUtils.isEmpty(tableMetas)) {
            return tableMetas.get(0);
        }
        return null;
    }
}
